﻿namespace LoginSample.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using LoginSample.Models;

    public class LoginController
    {
        public IUserDao UserDao { get; set; }

        public bool Register(string username, string password, string passwordConfirmation)
        {
            var existingUser = this.UserDao.GetByUsername(username);
            if (existingUser == null)
            {
                if (PasswordIsValid(password, passwordConfirmation))
                {
                    var user = new User(username, password);
                    this.UserDao.Add(user);
                    return true;
                }
            }

            return false;
        }

        private static bool PasswordIsValid(string password, string passwordConfirmation)
        {
            if (password.Length < 8 || password.Length > 32)
                return false;
            if (password != passwordConfirmation)
                return false;

            return true;
        }

        public bool Login(string username, string password)
        {
            var user = this.UserDao.GetByUsername(username);

            if (user != null)
            {
                if (PasswordMatches(password , user.Password))
                {
                    if(!user.IsBlocked)
                        return true;
                }
            }

            return false;
        }

        private bool PasswordMatches(string passwordLogin, string passwordBase)
        {
            return String.Equals(passwordBase, passwordLogin);
        }
    }
}
